package com.cy.pj.common.aspect;

import com.cy.pj.common.annotation.RequiredLog;
import com.cy.pj.sys.pojo.SysLog;
import com.cy.pj.sys.service.SysLogService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

import static com.sun.corba.se.impl.activation.ServerMain.logError;

@Aspect
@Component
@Slf4j
public class SysLogAspect {
    @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredLog)")
    public void doLog() {

    }
    @Around("doLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        try {
            long t1 = System.currentTimeMillis();
            Object result = joinPoint.proceed();
            long t2 = System.currentTimeMillis();
            System.out.println("time====" + (t2 - t1));
            saveSysLog(joinPoint, (t2 - t1));
            return result;
        } catch (Throwable e) {
            logError(joinPoint,e.getMessage());
            throw e;
        }

    }
    //将错误日志进行输出并记录
    private void logError(ProceedingJoinPoint joinPoint,String exceptionMsg) throws JsonProcessingException {
        String targetClassName=joinPoint.getTarget().getClass().getName();
        String methodName=joinPoint.getSignature().getName();
        String params=new ObjectMapper().writeValueAsString(joinPoint.getArgs());
        log.error("msg->{}->{}-{}",targetClassName+"."+methodName,params,exceptionMsg);
    }

    @Autowired
    private SysLogService sysLogService;

    private void saveSysLog(ProceedingJoinPoint joinPoint,long time) throws NoSuchMethodException, JsonProcessingException {
        Class<?> targetClass = joinPoint.getTarget().getClass();
        MethodSignature ms = (MethodSignature) joinPoint.getSignature();
        Method targetMethod = targetClass.getDeclaredMethod(ms.getName(), ms.getParameterTypes());
        RequiredLog requiredLog = targetMethod.getAnnotation(RequiredLog.class);
        String operation = requiredLog.value();
        SysLog entity = new SysLog();
        entity.setUsername("cgb");
        entity.setIp("201.123.201.100");
        entity.setOperation(operation);
        entity.setMethod(targetClass.getName()+"."+targetMethod.getName());
        //entity.setParams(Arrays.toString(joinPoint.getArgs()));
        entity.setParams(new ObjectMapper().writeValueAsString(joinPoint.getArgs()));
        entity.setTime(time);
        entity.setCreateDate(new Date());
        sysLogService.saveObject(entity);
    }
}
